//
//  QILoginViewController.swift
//  MLYY
//
//  Created by 秦江涛 on 2023/10/8.
//

import UIKit
import YYText

class QILoginViewController: UIViewController {
    
    private var getCodeBtn = GSCaptchaButton()
    private var phoneTextF = UITextField()
    private var codeTextF = UITextField()
    private var selectBtn = UIButton()
    /// true: 微信登录   false: 绑定微信
    private var isWXLogin = false

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        getCodeBtn.countdown = false
        NotificationCenter.default.removeObserver(self)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        title = "登录"

        addUI()
        getData()
        NotificationCenter.default.addObserver(self, selector: #selector(WXLoginMethod(ntf:)), name: NSNotification.Name(rawValue: "WXLogin"), object: nil)
    }
    
    private func getData() {
        QINetworkManager.getNetworkPermissions()
    }
    
    private func addUI() {
        self.view.addGradientColor(fromColors: [ColorWithStr("#FFD1D6").cgColor, ColorWithStr("#FFFFFF").cgColor, ColorWithStr("#F6F7F9").cgColor], locationArr: [0, 0.5, 1.0], with: .topToBottom)
        
        let title1L = UILabel().then({
            $0.frame = CGRect(x: 24, y: NAV_HEIGHT + 44, width: 200, height: 33)
            $0.text = "欢迎登录月升"
            $0.textColor = Color333333
            $0.font = SYSFONTBOLD(ofSize: 24)
        })
        view.addSubview(title1L)
        
        let leftView = UIView()
        leftView.frame = CGRect(x: 0, y: 0, width: 20, height: 0)
        phoneTextF = UITextField().then {
            $0.frame = CGRect(x: 24, y: title1L.bottom + 43, width: SCREEN_WIDTH - 50, height: 56)
            $0.backgroundColor = ColorEEEEEE
            $0.font = SYSFONT(ofSize: 16)
            $0.placeholder = "请输入手机号码"
//            $0.text = "15038384150"
            $0.keyboardType = .numberPad
            $0.leftView = leftView
            $0.leftViewMode = .always
            $0.addRoundedCorners(withRadius: 28)
        }
        view.addSubview(phoneTextF)
        
        let left1View = UIView()
        left1View.frame = CGRect(x: 0, y: 0, width: 20, height: 0)
        codeTextF = UITextField().then {
            $0.frame = CGRect(x: 24, y: phoneTextF.bottom + 20, width: SCREEN_WIDTH - 50, height: 56)
            $0.backgroundColor = ColorEEEEEE
            $0.font = SYSFONT(ofSize: 16)
            $0.placeholder = "验证码"
//            $0.text = "1234"
            $0.keyboardType = .numberPad
            $0.leftView = left1View
            $0.leftViewMode = .always
            $0.addRoundedCorners(withRadius: 20)
            $0.addBorder(withWidth: 1, borderColor: ColorEEEEEE)
        }
        view.addSubview(codeTextF)
        
        getCodeBtn = GSCaptchaButton().then {
            $0.frame = CGRect(x: codeTextF.width - 120, y: 0, width: 120, height: 56)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 13)
            $0.setTitle("获取验证码", for: .normal)
            $0.setTitle("重新获取：second秒", for: .disabled)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 28)
            $0.addTarget(self, action: #selector(getCodeBtnClick), for: .touchUpInside)
        }
        codeTextF.addSubview(getCodeBtn)
        
        let title2L = UILabel().then({
            $0.frame = CGRect(x: 24, y: codeTextF.bottom + 20, width: SCREEN_WIDTH - 48, height: 22)
            $0.text = "未注册的手机号验证后自动创建月升账号"
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
        })
        view.addSubview(title2L)
        
        let loginBtn = UIButton().then {
            $0.frame = CGRect(x: title1L.left, y: title2L.bottom + 75, width: codeTextF.width, height: 48)
            $0.backgroundColor = MainColor
            $0.titleLabel?.font = SYSFONT(ofSize: 14)
            $0.setTitle("登录", for: .normal)
            $0.setTitleColor(.white, for: .normal)
            $0.addRoundedCorners(withRadius: 24)
            $0.addTarget(self, action: #selector(loginBtnClick), for: .touchUpInside)
        }
        view.addSubview(loginBtn)
        
        
        let agreementL = YYLabel()
        agreementL.frame = CGRect(x: SCREEN_WIDTH / 2 - 110, y: loginBtn.bottom + 35, width: 240, height: 18)
        agreementL.font = SYSFONT(ofSize:  12)
        view.addSubview(agreementL)
        
        let attributedString = NSMutableAttributedString(string: "阅读并同意《用户协议》和《隐私政策》")
        let agree1 = "《用户协议》"
        let rang: NSRange = NSRange(location: 5, length: agree1.count)
        attributedString.yy_setTextHighlight(rang, color: MainColor, backgroundColor: .white) { _, _, _, _ in
            print("《用户用户协议》")
            let ctl = ProtocolViewController()
            ctl.titleStr = "用户协议"
            self.navigationController?.pushViewController(ctl, animated: true)
        }
        let agree3 = "《隐私政策》"
        let rang3: NSRange = NSRange(location: 12, length: agree3.count)
        attributedString.yy_setTextHighlight(rang3, color: MainColor, backgroundColor: .white) { _, _, _, _ in
            print(agree3)
            let ctl = ProtocolViewController()
            ctl.titleStr = "隐私政策"
            self.navigationController?.pushViewController(ctl, animated: true)
        }
        agreementL.attributedText = attributedString
        
        selectBtn = UIButton().then {
            $0.frame = CGRect(x: 0, y: 0, width: 20, height: 20)
            $0.centerY = agreementL.centerY
            $0.right = agreementL.left
            $0.isSelected = true
            $0.setImage(UIImage(named: "未选择"), for: .normal)
            $0.setImage(UIImage(named: "已选择"), for: .selected)
            $0.addTarget(self, action: #selector(selectBtnClick(btn: )), for: .touchUpInside)
        }
        view.addSubview(selectBtn)
        
        
        let title3L = UILabel().then({
            $0.frame = CGRect(x: 24, y: SCREEN_HEIGHT - 180, width: SCREEN_WIDTH - 48, height: 22)
            $0.text = "其他登录方式"
            $0.textAlignment = .center
            $0.textColor = Color333333
            $0.font = SYSFONT(ofSize: 14)
        })
        view.addSubview(title3L)
        
        let wxBtn = UIButton().then {
            $0.frame = CGRect(x: SCREEN_WIDTH / 2 - 24, y: title3L.bottom + 20, width: 48, height: 48)
            $0.setImage(UIImage(named: "微信登录"), for: .normal)
            $0.addTarget(self, action: #selector(wxBtnClick), for: .touchUpInside)
        }
        view.addSubview(wxBtn)
        
    }
    
    
    @objc private func getCodeBtnClick() {
        let phoneStr = phoneTextF.text ?? ""
        guard phoneStr.count > 0 else {
            ShowHUD(str: "请输入手机号")
            return
        }
        let parame = [
            "mobile": phoneStr,
            "event": "login"
        ]
        QINetworkManager.requestJson(urlStr: "/Sms/send", parameters: parame) { json in
            print(json)
            ShowHUD(str: "发送成功")
            self.getCodeBtn.maxSecond = 60
            self.getCodeBtn.countdown = true
        }
    }
    @objc private func loginBtnClick() {
        let phoneStr = phoneTextF.text ?? ""
        let codeStr = codeTextF.text ?? ""
        guard phoneStr.count > 0 else {
            ShowHUD(str: "请输入手机号")
            return
        }
        guard codeStr.count > 0 else {
            ShowHUD(str: "请输入验证码")
            return
        }
        guard selectBtn.isSelected == true else {
            ShowHUD(str: "请阅读并同意《用户协议》和《隐私政策》")
            return
        }
        let parame = [
            "mobile": phoneStr,
            "captcha": codeStr,
            "login_type": "1",      //登陆方式:1=手机号登录 2=微信登录 3=微信小程序登录
            "login_client": "1"     //登陆终端:1=App 2=微信小程序
        ]
        QINetworkManager.requestJson(urlStr: "/User/login", parameters: parame) { json in
            print(json)
            Defaults[\.isLogin] = true
            
            let window = UIApplication.shared.keyWindow
            window?.switchRootCtrl()
            
        } fail: { json in
            let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
            if model.code == 102 {  //绑定微信
                let bindingView = BindingWeChatView(frame: CGRect(x: 0, y: SCREEN_HEIGHT - 280, width: SCREEN_WIDTH, height: 280))
                QINPopUpTool.sharedInstance().popUp(with: bindingView, withToViewCtl: self, withAnimation: .bottom, withCanTapBgCancel: true, closeBefore: .node)
            } else if model.code == 105 {   //完善资料
                let ctl = ImproveInfoViewController()
                self.navigationController?.pushViewController(ctl, animated: true)
            } else if model.code == 106 || model.code == 107 {   //幸福感问卷调查
                let ctl = QuestionnaireSurveyViewController()
                ctl.code = model.code
                self.navigationController?.pushViewController(ctl, animated: true)
            }
        }
        
    }
    @objc private func selectBtnClick(btn: UIButton) {
        selectBtn.isSelected = !selectBtn.isSelected
    }
    
    @objc private func wxBtnClick() {
        guard selectBtn.isSelected == true else {
            ShowHUD(str: "请阅读并同意《用户协议》和《隐私政策》")
            return
        }
        let req = SendAuthReq()
        req.openID = "wx2e910e8ae30e14d1"
        req.scope = "snsapi_userinfo"
        req.state = "wx_oauth_authorization_state"
        WXApi.send(req) { isSuccess in
            print(isSuccess)
            if isSuccess {
                self.isWXLogin = true
            } else {
                //ShowHUD(str: "微信跳转失败")
            }
        }
    }
    
    @objc private func WXLoginMethod(ntf: Notification) {
        let code = "\(ntf.object ?? "")"
        if isWXLogin {
            let parame = [
                "wechat_code": code,
                "login_type": "2",
                "login_client": "1"
            ]
            QINetworkManager.requestJson(urlStr: "/User/login", parameters: parame) { json in
                print(json)
                Defaults[\.isLogin] = true
                
                let window = UIApplication.shared.keyWindow
                window?.switchRootCtrl()
                
            } fail: { json in
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                if model.code == 103 {  //绑定手机号
                    let bindingMobileCtl = BindingPhoneViewController()
                    self.navigationController?.pushViewController(bindingMobileCtl, animated: true)
                } else if model.code == 105 {   //完善资料
                    let ctl = ImproveInfoViewController()
                    self.navigationController?.pushViewController(ctl, animated: true)
                } else if model.code == 106 || model.code == 107 {   //幸福感问卷调查
                    let ctl = QuestionnaireSurveyViewController()
                    ctl.code = model.code
                    self.navigationController?.pushViewController(ctl, animated: true)
                }
                ShowHUD(str: model.msg)
            }
        } else {
            QINetworkManager.requestJson(urlStr: "/User/bindWechat", parameters: ["wechat_code": code]) { json in
                print(json)
            } fail: { json in
                let model = json.dictionaryObject?.kj.model(QIBaseModel.self) ?? QIBaseModel()
                if model.code == 103 {  //绑定手机号
                    let bindingMobileCtl = BindingPhoneViewController()
                    self.navigationController?.pushViewController(bindingMobileCtl, animated: true)
                } else if model.code == 105 {   //完善资料
                    let ctl = ImproveInfoViewController()
                    self.navigationController?.pushViewController(ctl, animated: true)
                } else if model.code == 106 || model.code == 107 {   //幸福感问卷调查
                    let ctl = QuestionnaireSurveyViewController()
                    ctl.code = model.code
                    self.navigationController?.pushViewController(ctl, animated: true)
                }
                ShowHUD(str: model.msg)
            }
        }
        
    }
    
    deinit {
        getCodeBtn.countdown = false
        NotificationCenter.default.removeObserver(self)
    }

}
